package com.calvin.study.multithread.safe.pc.nosafe;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class NotSafeDataBuffer<T> {

	public static final int MAX_AMOUNT = 10;
	private List<T> dataList = new LinkedList<>();

	private AtomicInteger amount = new AtomicInteger(0);

	// 向数据区增加一个元素
	public void add(T element) throws Exception {
		if (amount.get() > MAX_AMOUNT) {
			System.out.println("队列已经满了！ ");
			return;
		}
		dataList.add(element);
		System.out.println(element + "");
		amount.incrementAndGet();
		// 如果数据不一致， 抛出异常
		if (amount.get() != dataList.size()) {
			throw new Exception(amount + "!=" + dataList.size());
		}
	}

	public T fetch() throws Exception {
		if (amount.get() <= 0) {
			System.out.println("队列已经空了！ ");
			return null;
		}
		T element = dataList.remove(0);
		System.out.println(element + "");
		amount.decrementAndGet();
		// 如果数据不一致， 抛出异常
		if (amount.get() != dataList.size()) {
			throw new Exception(amount + "!=" + dataList.size());
		}
		return element;
	}

}
